package org.example.JVM.ByteCode.Util;

import org.example.JVM.ByteCode.Type.U2;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:access_flags的值
 * @author: farprt
 * @create: 2022-11-13 13:47
 **/
public class ClassAccessFlagUtils {

    private static final Map<Integer, String> classAccessFlagMap = new HashMap<>();

    static {
        //公有类型
        classAccessFlagMap.put(0x0001, "public");
        //不允许有子类
        classAccessFlagMap.put(0x0010, "final");

        classAccessFlagMap.put(0x0020, "super");
        //接口
        classAccessFlagMap.put(0x0200, "interface");
        //抽象类
        classAccessFlagMap.put(0x0400, "abstract");
        //该class非java代码编译后生成
        classAccessFlagMap.put(0x1000, "synthetic");
        //注解类型
        classAccessFlagMap.put(0x2000, "annotation");
        //枚举类型
        classAccessFlagMap.put(0x4000, "enum");
    }

    /**
     * @param flag
     * @return: {@link String}
     * @Author: farprt
     * @date: 2022/11/13 16:43
     * @description: 获取16进制对应的访问标志字符串表示（仅用于类的访问标志）
     */
    public static String toClassAccessFlagsString(U2 flag) {
        final int flagValue = flag.toInt();
        StringBuilder flagBuild = new StringBuilder();
        classAccessFlagMap.keySet()
                .forEach(key -> {
                    if ((flagValue & key) == key) {
                        flagBuild.append(classAccessFlagMap.get(key)).append(",");
                    }
                });
        return (flagBuild.length() > 0 && flagBuild.charAt(flagBuild.length() - 1) == ',') ?
                flagBuild.substring(0, flagBuild.length() - 1) : flagBuild.toString();
    }

}